<?php

namespace app\v1_0\controller\company;

use app\common\logic\ResumeEmailLogic;
use app\common\logic\ResumeLogic;
use app\common\logic\ResumeParseLogic;
use think\Exception;

class ResumeEmailCron extends \app\v1_0\controller\common\Base {

    public function _initialize() {
        parent::_initialize();
    }

    public function run() {
//        dolog(__METHOD__,'running');
        //上锁
        $key = 'resume_email_cron';
        $is_run = cache($key);
        if ($is_run) {
            $this->ajaxReturn(200, '执行中');
        }
        cache($key, time(), 3600);
        try{
            $resList = [];
            $where = [
                'synctime' => ['elt', time() - 60],
                'status' => 1
            ];
            $list = model('ResumeEmail')->where($where)->limit(10)->order('synctime asc')->select();
            if ($list) {
                $ids = array_column($list, 'id');
                model('ResumeEmail')->whereIn('id', $ids)->update(['synctime' => time()]);
                foreach ($list as $item) {
                    $res = ResumeLogic::syncEmail($item['id']);
                    $resList[] = [
                        'email' => $item['name'],
                        'res' => $res
                    ];
                }
            }
            //解锁
            cache($key, null);
            $this->ajaxReturn(200, '执行成功', $resList);
        }catch (Exception $e){
            //解锁
            cache($key, null);
            throw new Exception();
        }
    }

//    public function test(){
//        $emailId = 14;
//        $emailInfo = model('ResumeEmail')->where(['id' => $emailId])->find();
//        $email = new ResumeEmailLogic($emailInfo['name'], $emailInfo['pwd']);
//        $total = $email->getTotalNum();
//        $id = $total;
//        $header = $email->getHeader($id);
//        $body = $email->getBody($id);
//
//        $tempDir = '/tmp/html';
//        if (!is_dir($tempDir)) {
//            mkdir($tempDir, 0777, true);
//        }
//        $attachment = $tempDir . '/' . uniqid() . '.html';
//        file_put_contents($attachment, $body);
//
//        $data = ResumeParseLogic::fileParse($attachment);
//        print_r($data);exit;
//    }

}
